from odoo import fields, models, api
from odoo.addons.rp_customer_management.models.primary.rp_flow_log import CHANGE_TYPE, RECORD_SELECTION
from odoo.addons.rp_shipment_management.functions.ship_order_fc import ShipOrderFC
from odoo.exceptions import UserError
from ...functions.ship_order_fc import ShipOrderFC as ShipOrder
from ...functions.shipment_fc import ShipmentFC as Shipment
from odoo.addons.rp_courier_management.models.setting.rp_value_added_service import VALUE_CATEGORY
from odoo.addons.rp_courier_management.models.primary.rp_courier_mail_route import FULFILLMENT_TYPE
from odoo.addons.rp_customer_management.models.inherit.res_partner_inherit_for_customer import ADDRESS_TYPE
from odoo.addons.rp_courier_management.models.primary.rp_courier_mail_route import EXPRESS_CATEGORY

SHIP_ORDER_STATE = [('one', '第一步'), ('two', '第二步'), ('three', '第三步'), ('four', '第四步'), ('five', '第五步'), ('six', '第六步'), ('unpaid', '待支付'), ('done', '已支付'), ('fail', '支付失败'), ('invoiced', '已开票')]
PROCESS_STEP = [('coupon', '优惠券'), ('balance', '余额'), ('pay', '支付')]


class RPShipOrder(models.Model):
    _name = 'rp.ship.order'
    _description = '运输订单'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _rec_name = 'code'
    _order = 'create_date DESC'

    def _default_get_customer(self):
        rcd = self.env['rp.customer'].search([('name', '=', 'admin')])
        return rcd.id if rcd else False

    code = fields.Char(string='订单单号', default='RP_SO/20230101/*****', readonly=True, copy=False, index=True, tracking=True)

    btn_state = fields.Selection(string='按钮状态', selection=SHIP_ORDER_STATE, default='one')
    state = fields.Selection(string='状态', selection=SHIP_ORDER_STATE, default='one', compute='_compute_state', store=True, copy=False, tracking=True)
    customer_id = fields.Many2one(string='客户', comodel_name='rp.customer', default=_default_get_customer, tracking=True)

    step_one = fields.Boolean(string='第一步', default=False, compute='_depends_compute_step_one', store=True, copy=False)
    send_country_id = fields.Many2one(string='发件国家', comodel_name='res.country', tracking=True)
    send_postal_code_id = fields.Many2one(string='发件邮编', comodel_name='rp.postal.code', tracking=True)
    receive_country_id = fields.Many2one(string='收件国家', comodel_name='res.country', tracking=True)
    receive_postal_code_id = fields.Many2one(string='收件邮编', comodel_name='rp.postal.code', tracking=True)
    invoice_postal_code_id = fields.Many2one(string='发票邮递邮编', comodel_name='rp.postal.code', tracking=True)
    package_type_id = fields.Many2one(string='包裹类型', comodel_name='rp.package.type', tracking=True)
    no_have_back = fields.Boolean(string='没有上一步', default=False)
    is_frist_step = fields.Boolean(string='判断第一步', default=False)
    # step one end

    step_two = fields.Boolean(string='第二步', default=False, compute='_depends_compute_step_two', store=True, copy=False)
    rp_parcel_ids = fields.One2many(string='包裹详情', comodel_name='rp.parcel', inverse_name='rp_ship_order_id', tracking=True)
    parcel_total_weight = fields.Float(string='包裹总重量', digits=(8, 3), default=0, compute='_depends_rp_parcel_ids', store=True)
    parcel_total_volume = fields.Float(string='包裹总体积', digits=(8, 3), default=0, compute='_depends_rp_parcel_ids', store=True)
    parcel_total_values = fields.Float(string='包裹总价值', digits=(8, 3), default=0, compute='_depends_rp_parcel_ids', store=True)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)
    is_second_step = fields.Boolean(string='判断第二步', default=False)
    # step two end

    step_three = fields.Boolean(string='第三步', default=False, compute='_depends_step_three', store=True, copy=False)
    shipper_mail_route_id = fields.Many2one(string='托运商邮路', comodel_name='rp.shipper.mail.route', tracking=True)
    express_category = fields.Selection(string='发件类型', selection=EXPRESS_CATEGORY, copy=False)
    same_city_flag = fields.Boolean(string='同城')
    same_province_flag = fields.Boolean(string='同省')
    shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper', store=True)
    aging_id = fields.Many2one(string='时效', comodel_name='rp.aging')
    expect_arrive_date = fields.Date(string='预计到达时间')
    parcel_actual_weight = fields.Float(string='包裹实际重量', digits=(8, 3), default=0, store=True, help='通过体重比公式比较后的重量')
    parcel_rounded_weight = fields.Float(string='包裹取整重量', digits=(8, 3), default=0, store=True, help='实际重量通过进位后的重量')
    is_third_step = fields.Boolean(string='判断第三步', default=False)
    # international_flag = fields.Boolean(string='国际邮路', default=False, compute='_depends_step_three', store=True)
    # step three end

    step_four = fields.Boolean(string='第四步', default=False, compute='_depends_step_four', store=True, copy=False)
    rp_ship_order_fulfillment_line_ids = fields.One2many(string='头尾程明细', comodel_name='rp.ship.order.fulfillment.line', inverse_name='rp_ship_order_id')
    operation_dropoff = fields.Boolean(string='网点收件', related='shipper_mail_route_id.operation_dropoff', readonly=True)
    fulfillment_dropoff = fields.Boolean(string='网点收件')
    operation_pickup = fields.Boolean(string='上门取件', related='shipper_mail_route_id.operation_pickup', readonly=True)
    fulfillment_pickup = fields.Boolean(string='上门取件')
    operation_collect = fields.Boolean(string='网点取件', related='shipper_mail_route_id.operation_collect', readonly=True)
    fulfillment_collect = fields.Boolean(string='网点取件')
    operation_delivery = fields.Boolean(string='送货上门', related='shipper_mail_route_id.operation_delivery', readonly=True)
    fulfillment_delivery = fields.Boolean(string='送货上门')

    rp_ship_order_value_added_line_ids = fields.One2many(string='增值服务明细', comodel_name='rp.ship.order.value.added.line', inverse_name='rp_ship_order_id')
    all_value_added_line_ids = fields.Many2many('rp.value.added.service', 'rp_all_value_added_service_rel', 'rp_ship_order_id', 'value_added_id',
                                                compute='_compute_all_value_added_line_ids',
                                                string='全部可用的增值服务')
    select_value_added_line_ids = fields.Many2many('rp.value.added.service', "rp_select_value_added_rel", 'rp_ship_order_id', 'value_added_id',
                                                   string='可用的增值服务')

    four_rp_parcel_ids = fields.One2many(string='包裹详情', comodel_name='rp.parcel', inverse_name='rp_ship_order_id')
    is_parcel_message = fields.Boolean(string='包裹信息', compute='_compute_is_parcel_message')
    fulfillment_listener = fields.Integer(string='头尾程监听', compute='_depends_fulfillment_listener', store=True)
    is_fourth_step = fields.Boolean(string='判断第四步', default=False)
    # step four end

    step_five = fields.Boolean(string='第五步', default=False, compute='_depends_step_five', store=True, copy=False)
    email = fields.Char(string='邮箱', help='历史遗留字段', compute='depends_on_receive_email')

    send_email = fields.Char(string='发件人邮箱')
    receive_email = fields.Char(string='收件人邮箱')

    send_state_id = fields.Many2one(string='发件省', comodel_name='res.country.state', compute='_depends_send_postal_code_id', store=True)
    send_city_id = fields.Many2one(string='发件市', comodel_name='res.city', compute='_depends_send_postal_code_id', store=True)
    send_street = fields.Char(string='发件街道', tracking=True)
    send_street2 = fields.Char(string='发件街道2')
    send_first_name = fields.Char(string='发件人名', tracking=True)
    send_last_name = fields.Char(string='发件人姓', tracking=True)
    send_phone_areacode = fields.Char(string='发件电话区号', tracking=True)
    send_phone = fields.Char(string='发件电话', tracking=True)
    send_address_type = fields.Selection(string='发件地址类型', selection=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0], tracking=True)
    send_company_name = fields.Char(string='发件公司名称', tracking=True)

    receive_state_id = fields.Many2one(string='收件省', comodel_name='res.country.state', compute='_depends_receive_postal_code_id', store=True)
    receive_city_id = fields.Many2one(string='收件市', comodel_name='res.city', compute='_depends_receive_postal_code_id', store=True)
    receive_street = fields.Char(string='收件街道1', tracking=True)
    receive_street2 = fields.Char(string='收件街道2')
    receive_first_name = fields.Char(string='收件人名', tracking=True)
    receive_last_name = fields.Char(string='收件人姓', tracking=True)
    receive_phone_areacode = fields.Char(string='收件电话区号', tracking=True)
    receive_phone = fields.Char(string='收件电话', tracking=True)
    receive_address_type = fields.Selection(string='发件地址类型', selection=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0], tracking=True)
    receive_company_name = fields.Char(string='收件公司名称', tracking=True)

    need_invoice = fields.Boolean(string='发票', help='需要发票进行勾选')
    copy_from_sender = fields.Boolean(string='从发件复制')
    invoice_state_id = fields.Many2one(string='发票邮寄省', comodel_name='res.country.state', compute='depends_on_invoice_postal_id', store=True)
    invoice_city_id = fields.Many2one(string='发票邮寄市', comodel_name='res.city', compute='depends_on_invoice_postal_id', store=True)
    invoice_receive_street = fields.Char(string='发票邮寄街道', tracking=True)
    invoice_receive_street2 = fields.Char(string='发票邮寄街道2', tracking=True)
    invoice_first_name = fields.Char(string='发票邮寄人名', tracking=True)
    invoice_last_name = fields.Char(string='发票邮寄人姓', tracking=True)
    invoice_phone_areacode = fields.Char(string='发票邮寄人电话区号', tracking=True)
    invoice_phone_number = fields.Char(string='发票邮寄人电话', tracking=True)
    invoice_address_type = fields.Selection(string='发票邮寄地址类型', selection=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0], tracking=True)
    invoice_email = fields.Char(string='发票邮寄人邮箱', tracking=True)
    invoice_company_name = fields.Char(string='发票邮寄地址公司名称', tracking=True)

    is_fifth_step = fields.Boolean(string='判断第五步', default=False)
    # step five end

    step_six = fields.Boolean(string='第六步', default=False, compute='_depends_step_six', store=True, copy=False, help='包含：开票,暂时空白')
    is_sixth_step = fields.Boolean(string='判断第六步', default=False)

    pay_link = fields.Char(string='支付链接', store=True)
    # 配置定价
    mail_route_tag_price = fields.Float(string='邮路定价', digits=(8, 3), default=0, store=True)
    fulfillment_total_tag_price = fields.Float(string='头尾程总标价', digits=(8, 3), default=0, compute='_depends_compute_tag_price', store=True)
    value_added_total_tag_price = fields.Float(string='增值服务(二类)总标价', digits=(8, 3), default=0, compute='_depends_compute_tag_price', store=True)
    total_tag_price = fields.Float(string='总标价', digits=(8, 3), default=0, compute='_depends_compute_tag_price', store=True)

    # 销售调价
    mail_route_sale_adjusted_price = fields.Float(string='邮路销售调后价', digits=(8, 3), default=0, store=True)
    used_sale_price_adjust_ids = fields.Many2many(string='使用销售调价', comodel_name='rp.shipper.sale.price.adjustment', readonly=True,
                                                  relation='rp_ship_order_and_sale_price_adjustment_rel', column1='ship_order_id', column2='sale_price_adjustment_id')
    fulfillment_total_sale_adjusted_price = fields.Float(string='头尾程销售总调后价', digits=(8, 3), default=0, compute='_depends_compute_sale_price', store=True)
    value_added_total_sale_adjusted_price = fields.Float(string='增值服务(二类)销售总调后价', digits=(8, 3), default=0, compute='_depends_compute_sale_price', store=True)
    total_sale_adjusted_price = fields.Float(string='销售总调后价', digits=(8, 3), default=0, compute='_depends_compute_sale_price', store=True)

    # 运单使用价格
    mail_route_actual_price = fields.Float(string='邮路实价', digits=(8, 3), default=0, compute='_depends_compute_actual_price', store=True)
    fulfillment_total_actual_price = fields.Float(string='头尾程总实价', digits=(8, 3), default=0, compute='_depends_compute_actual_price', store=True)
    value_added_total_actual_price = fields.Float(string='增值服务(二类)总实价', digits=(8, 3), default=0, compute='_depends_compute_actual_price', store=True)
    total_actual_price = fields.Float(string='总实价', digits=(8, 3), default=0, compute='_depends_compute_actual_price', store=True)

    pay_flag = fields.Boolean(string='支付成功标志', default=False, copy=False, tracking=True)
    fail_flag = fields.Boolean(string='支付失败标志', default=False, copy=False, tracking=True)
    invoice_flag = fields.Boolean(string='发票开具标志', default=False, copy=False, tracking=True)
    click_pay_flag = fields.Boolean(string='点击支付的标志', help='主要是为了显示支付单', default=False)
    # step six end

    shipment_ids = fields.Many2many(string='运输单', comodel_name='rp.shipment', relation='rp_ship_order_and_shipment_rel', column1='ship_order_id', column2='shipment_id')
    shipment_number = fields.Integer(string='运输单数量', default=0, compute='_depends_compute_shipment_number', store=True)
    shipment_flag = fields.Boolean(string='有效运单', default=False, compute='_depends_compute_shipment_number', store=True)

    remarks = fields.Char(string='备注')
    active = fields.Boolean(string='有效', help='方便逻辑删除订单', default=True, tracking=True)

    # 余额折扣等流程字段
    balance_tag = fields.Boolean(string='余额', default=False)
    balance_price = fields.Float(string='余额扣减金额', digits=(12, 5))
    process_step = fields.Selection(string='流程步骤', selection=PROCESS_STEP, default=False)

    """
    Native Function
    """

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.ship.order') or '/'
        return super(RPShipOrder, self).create(vals_list)

    def write(self, values):
        if self.state in ['done', 'invoiced']:
            if self.state == 'done':
                if set(list(values.keys())) & {'need_invoice', 'copy_from_sender', 'invoice_state_id', 'invoice_city_id', 'invoice_receive_street', 'invoice_receive_street2', 'invoice_first_name',
                                               'invoice_last_name', 'invoice_phone_number', 'invoice_address_type', 'invoice_email', 'invoice_company_name', 'shipment_flag', 'shipment_number', 'state', 'invoice_flag'}:
                    return super(RPShipOrder, self).write(values)
                else:
                    raise UserError('订单已经支付完成，不能修改！')
            elif self.state == 'invoiced':
                if set(list(values.keys())) & {'shipment_flag', 'shipment_number', 'state', 'step_five', 'step_six', 'state'}:
                    return super(RPShipOrder, self).write(values)
                else:
                    raise UserError('订单已经开票，不能修改!')
            else:
                raise UserError('订单已经开票，不能修改!')
        else:
            return super(RPShipOrder, self).write(values)

    """
    Common
    """

    # 选择头尾程
    # 添加头尾程明细和对应的增值服务
    def _add_fulfillment(self, type):
        available_sff_values = ShipOrder(self.env).backdoor_get_fulfillment(self.shipper_mail_route_id)
        filtered_data = list(filter(lambda x: x['operation_type'] == type, available_sff_values))
        available_sff = self.env['rp.available.shipper.fulfillment.tran'].create(filtered_data)
        value_added = self.env['rp.value.added.service'].search([('name', '=', type)])
        self.write({'rp_ship_order_fulfillment_line_ids': [(0, 0, {'rp_ship_order_id': self.id,
                                                                   'name': available_sff.operation_name,
                                                                   'operation_type': available_sff.operation_type,
                                                                   'available_flag': available_sff.available_flag,
                                                                   'use_flag': True})],
                    'rp_ship_order_value_added_line_ids': [(0, 0, {'rp_ship_order_id': self.id,
                                                                   'value_added_id': value_added.id,
                                                                   'value_added_type': value_added.type,
                                                                   'tag_price': available_sff.tag_price,
                                                                   'sale_adjusted_price': available_sff.sale_adjusted_price,
                                                                   'used_sale_price_adjust_ids': [(6, 0, available_sff.used_sale_price_adjust_ids.ids)], })]})

    # 清空头尾程明细和增值服务明细
    def _unlink_fulfillment(self, type):
        fulfillment_ids = self.rp_ship_order_fulfillment_line_ids.filtered(lambda x: x.operation_type == type)
        value_added_ids = self.rp_ship_order_value_added_line_ids.filtered(lambda x: x.value_added_id.name == type)
        self.write({'rp_ship_order_fulfillment_line_ids': [(2, fulfillment_ids.id)],
                    'rp_ship_order_value_added_line_ids': [(2, value_added_ids.id)]})

    def record_flow_info(self):
        # 记录流水信息
        category_id = self.env['rp.flow.record.category'].search([('name', '=', '订单'), ('validate_flag', '=', True)]).id
        category_mail_id = self.env['rp.flow.record.category'].search([('name', '=', '邮路'), ('parent_category_id', '=', category_id)]).id
        category_fulfillment_id = self.env['rp.flow.record.category'].search([('name', '=', '头尾程'), ('parent_category_id', '=', category_id)]).id
        category_added_id = self.env['rp.flow.record.category'].search([('name', '=', '增值服务'), ('parent_category_id', '=', category_id)]).id
        log_detail_list = []
        if self.mail_route_actual_price > 0.0:
            log_detail_list.append((0, 0, {'flow_record_category_id': category_mail_id, 'change_type': CHANGE_TYPE[1][0], 'funds_change': self.mail_route_actual_price, 'desc': '邮路花费：' + str(self.mail_route_actual_price) + '€'}))
        if self.fulfillment_total_actual_price > 0.0:
            log_detail_list.append(
                (0, 0, {'flow_record_category_id': category_fulfillment_id, 'change_type': CHANGE_TYPE[1][0], 'funds_change': self.fulfillment_total_actual_price, 'desc': '头尾程花费：' + str(self.fulfillment_total_actual_price) + '€'}))
        if self.value_added_total_actual_price > 0.0:
            log_detail_list.append(
                (0, 0, {'flow_record_category_id': category_added_id, 'change_type': CHANGE_TYPE[1][0], 'funds_change': self.value_added_total_actual_price, 'desc': '增值服务花费：' + str(self.value_added_total_actual_price) + '€'}))
        data = {
            'rp_customer_id': self.customer_id.id,
            'category_id': category_id,
            'related_record': RECORD_SELECTION[0][0] + ',' + str(self.id),
            'change_type': CHANGE_TYPE[1][0],
            'funds_change': self.total_actual_price,
            'rp_flow_record_log_line_ids': log_detail_list
        }
        self.env['rp.flow.log'].create([data])

    def _create_shipment(self):
        """ 创建运单 """
        shipment = Shipment(self.env).backdoor_create_shipment(self)
        self.write({'shipment_ids': [(4, shipment.id, 0)]})

    def action_recreate_shipment(self):
        """ 补运单 """
        if self.state != SHIP_ORDER_STATE[7][0]:
            raise UserError('不在完成态，无法补单')
        self._create_shipment()

    """
    Depends
    """

    @api.depends('send_email')
    def depends_on_receive_email(self):
        for record in self:
            if record.send_email:
                self.email = record.send_email
            else:
                self.email = False

    @api.depends('send_country_id', 'send_postal_code_id', 'receive_country_id', 'receive_postal_code_id', 'package_type_id')
    def _depends_compute_step_one(self):
        """ 判断第一步是否完成 """
        for s in self:
            if all([s.send_country_id, s.send_postal_code_id, s.receive_country_id, s.receive_postal_code_id, s.package_type_id]):
                s.write({'step_one': True})
            else:
                s.write({'step_one': False})

    @api.depends('send_postal_code_id')
    def _depends_send_postal_code_id(self):
        """ 填入发件邮编自动填充发件省、市 """
        for s in self:
            if s.send_postal_code_id:
                s.write({'send_state_id': s.send_postal_code_id.state_id.id,
                         'send_city_id': s.send_postal_code_id.city_id.id})

    @api.depends('receive_postal_code_id')
    def _depends_receive_postal_code_id(self):
        """ 填入收件邮编自动填充收件省、市 """
        for s in self:
            if s.receive_postal_code_id:
                s.write({'receive_state_id': s.receive_postal_code_id.state_id.id,
                         'receive_city_id': s.receive_postal_code_id.city_id.id})

    @api.depends('invoice_postal_code_id')
    def depends_on_invoice_postal_id(self):
        """填入发票邮编自动填充发票省，市"""
        for s in self:
            if s.invoice_postal_code_id:
                s.write({'invoice_state_id': s.invoice_postal_code_id.state_id.id,
                         'invoice_city_id': s.invoice_postal_code_id.city_id.id})

    @api.depends('rp_parcel_ids.weight', 'rp_parcel_ids.depth', 'rp_parcel_ids.width', 'rp_parcel_ids.height', 'rp_parcel_ids.values')
    def _depends_rp_parcel_ids(self):
        """ 计算体积和重量 """
        for s in self:
            if s.rp_parcel_ids:
                total_weight, total_volume, total_values = 0.0, 0.0, 0.0
                for parcel in s.rp_parcel_ids:
                    if parcel.weight:
                        total_weight += parcel.weight
                    if parcel.volume:
                        total_volume += parcel.volume
                    if parcel.values:
                        total_values += parcel.values
                s.write({'parcel_total_weight': total_weight,
                         'parcel_total_volume': total_volume,
                         'parcel_total_values': total_values})

    @api.depends('parcel_total_weight', 'parcel_total_volume', 'parcel_total_values')
    def _depends_compute_step_two(self):
        """ 判断第二步是否完成 """
        for s in self:
            if all([s.parcel_total_weight != 0, s.parcel_total_volume != 0]):
                s.write({'step_two': True}) if s.step_one else s.write({'step_two': False})
            else:
                s.write({'step_two': False})

    @api.depends('shipper_mail_route_id')
    def _depends_step_three(self):
        """ 给予第四步头尾程默认值
            判断第三步是否完成 """
        for s in self:
            s.write({
                'fulfillment_dropoff': False,
                'fulfillment_pickup': False,
                'fulfillment_collect': False,
                'fulfillment_delivery': False,
                'rp_ship_order_fulfillment_line_ids': [(6, 0, [])],
                'rp_ship_order_value_added_line_ids': [(6, 0, [])],
                'select_value_added_line_ids': [(6, 0, [])]
            })
            if not (s.shipper_mail_route_id.operation_dropoff and s.shipper_mail_route_id.operation_pickup):
                s.write({
                    'fulfillment_dropoff': s.shipper_mail_route_id.operation_dropoff,
                    'fulfillment_pickup': s.shipper_mail_route_id.operation_pickup,
                })
            if s.shipper_mail_route_id.operation_dropoff and s.shipper_mail_route_id.operation_pickup:
                s.write({
                    'fulfillment_dropoff': False,
                    'fulfillment_pickup': True,
                })
            if not (s.shipper_mail_route_id.operation_collect and s.shipper_mail_route_id.operation_delivery):
                s.write({
                    'fulfillment_collect': s.shipper_mail_route_id.operation_collect,
                    'fulfillment_delivery': s.shipper_mail_route_id.operation_delivery,
                })
            if s.shipper_mail_route_id.operation_collect and s.shipper_mail_route_id.operation_delivery:
                s.write({
                    'fulfillment_collect': False,
                    'fulfillment_delivery': True,
                })
            s._onchange_fulfillment_dropoff()
            s._onchange_fulfillment_pickup()
            s._onchange_fulfillment_collect()
            s._onchange_fulfillment_delivery()

            if all([s.shipper_id, s.parcel_actual_weight, s.parcel_rounded_weight, s.shipper_mail_route_id]):
                s.write({'step_three': True}) if s.step_two else s.write({'step_three': False})
            else:
                # 方便接口清除数据使用
                s.write({'step_three': False})

    # 计算全部可用的增值服务
    @api.depends('shipper_mail_route_id')
    def _compute_all_value_added_line_ids(self):
        for rec in self:
            value_added_ids = rec.shipper_mail_route_id.value_added_ids.filtered(lambda x: x.category != 'one').ids
            if value_added_ids:
                rec.all_value_added_line_ids = [(6, 0, value_added_ids)]
            else:
                rec.all_value_added_line_ids = [(6, 0, [])]

    @api.depends('rp_parcel_ids.desc', 'rp_parcel_ids.values')
    def _compute_is_parcel_message(self):
        for rec in self:
            is_parcel_message = True
            for parcel in rec.rp_parcel_ids:
                if not parcel.desc or not parcel.values:
                    is_parcel_message = False
                    break
            rec.is_parcel_message = is_parcel_message

    @api.depends('rp_ship_order_fulfillment_line_ids')
    def _depends_fulfillment_listener(self):
        for s in self:
            number = 0
            if s.env.context.get('edit'):
                s.write({'fulfillment_listener': 3})
            elif s.rp_ship_order_fulfillment_line_ids:
                for ff in s.rp_ship_order_fulfillment_line_ids:
                    if ff.use_flag and ff.operation_type in [FULFILLMENT_TYPE[0][0], FULFILLMENT_TYPE[1][0]]:
                        number += 1
                    elif ff.use_flag and ff.operation_type in [FULFILLMENT_TYPE[2][0], FULFILLMENT_TYPE[3][0]]:
                        number += 2
                s.write({'fulfillment_listener': number})

    @api.depends('mail_route_tag_price', 'rp_ship_order_value_added_line_ids.tag_price')
    def _depends_compute_tag_price(self):
        """计算定价"""
        for s in self:
            total_tag_price = 0.000

            fulfillment_total_tag_price = sum(va.tag_price for va in s.rp_ship_order_value_added_line_ids.filtered(lambda i: i.value_added_category == VALUE_CATEGORY[0][0]))
            value_added_total_tag_price = sum(va.tag_price for va in s.rp_ship_order_value_added_line_ids.filtered(lambda i: i.value_added_category == VALUE_CATEGORY[1][0]))

            total_tag_price += s.mail_route_tag_price
            total_tag_price += fulfillment_total_tag_price
            total_tag_price += value_added_total_tag_price

            s.write({'fulfillment_total_tag_price': fulfillment_total_tag_price,
                     'value_added_total_tag_price': value_added_total_tag_price,
                     'total_tag_price': total_tag_price})

    @api.depends('mail_route_sale_adjusted_price', 'rp_ship_order_value_added_line_ids.sale_adjusted_price')
    def _depends_compute_sale_price(self):
        """ 计算销售调后价 """
        for s in self:
            total_sale_adjusted_price = 0.000

            fulfillment_total_sale_adjusted_price = sum(va.sale_adjusted_price for va in s.rp_ship_order_value_added_line_ids.filtered(lambda i: i.value_added_category == VALUE_CATEGORY[0][0]))
            value_added_total_sale_adjusted_price = sum(va.sale_adjusted_price for va in s.rp_ship_order_value_added_line_ids.filtered(lambda i: i.value_added_category == VALUE_CATEGORY[1][0]))

            total_sale_adjusted_price += s.mail_route_sale_adjusted_price
            total_sale_adjusted_price += fulfillment_total_sale_adjusted_price
            total_sale_adjusted_price += value_added_total_sale_adjusted_price
            s.write({'fulfillment_total_sale_adjusted_price': fulfillment_total_sale_adjusted_price,
                     'value_added_total_sale_adjusted_price': value_added_total_sale_adjusted_price,
                     'total_sale_adjusted_price': total_sale_adjusted_price})

    @api.depends('rp_parcel_ids.desc', 'rp_parcel_ids.values', 'rp_ship_order_fulfillment_line_ids.operation_type')
    def _depends_step_four(self):
        """ 判断第四步是否完成 """
        for s in self:
            # 方便接口修改头尾程信息
            if s.env.context.get('edit'):
                s.update({'step_four': True})
            else:
                n = 0
                for parcel in s.rp_parcel_ids:
                    if not all([parcel.desc, parcel.values != 0.0]):
                        n += 1
                if s.step_three:
                    head_data = self.rp_ship_order_fulfillment_line_ids.filtered(lambda x: x.operation_type in ['dropoff', 'pickup'])
                    if len(head_data) > 1:
                        raise UserError('头程配置错误')
                    if len(head_data) == 0:
                        n += 1
                    tail_data = self.rp_ship_order_fulfillment_line_ids.filtered(lambda x: x.operation_type in ['collect', 'delivery'])
                    if len(tail_data) > 1:
                        raise UserError('尾程配置错误')
                    if len(tail_data) == 0:
                        n += 1
                if not s.step_three:
                    n += 1
                s.update({'step_four': True}) if n == 0 else s.update({'step_four': False})

    @api.depends('send_first_name', 'send_last_name', 'send_street', 'send_phone', 'send_phone_areacode',
                 'receive_first_name', 'receive_last_name', 'receive_street', 'receive_phone', 'email', 'receive_phone_areacode',
                 'invoice_state_id', 'invoice_city_id', 'invoice_receive_street', 'invoice_first_name', 'invoice_phone_areacode',
                 'invoice_last_name', 'invoice_address_type', 'invoice_phone_number', 'invoice_email',
                 'invoice_company_name')
    def _depends_step_five(self):
        """ 判断第五步是否完成 """
        for s in self:
            if s.step_three and s.fulfillment_listener != 3:
                raise UserError('头尾程配置错误')
            if all([s.send_first_name, s.send_last_name, s.send_street, s.send_phone,
                    s.receive_first_name, s.receive_last_name, s.receive_street, s.receive_phone, s.email]):
                if s.need_invoice:
                    if all([s.invoice_receive_street, s.invoice_first_name, s.invoice_last_name,
                            s.invoice_phone_number, s.invoice_state_id, s.invoice_city_id]):
                        if s.invoice_address_type == 'commercial':
                            if not s.invoice_company_name:
                                s.update({'step_five': False})
                            else:
                                s.update({'step_five': True}) if s.step_four else s.update({'step_five': False})
                        else:
                            s.update({'step_five': True}) if s.step_four else s.update({'step_five': False})
                    else:
                        s.update({'step_five': False})
                s.update({'step_five': True}) if s.step_four else s.update({'step_five': False})
            else:
                s.update({'step_five': False})

    @api.depends('step_five')
    def _depends_step_six(self):
        """ 判断第六步是否完成 """
        for s in self:
            s.update({'step_six': True}) if s.step_five else s.update({'step_six': False})

    @api.depends('step_one', 'step_two', 'step_three', 'step_four', 'step_five', 'step_six', 'pay_flag', 'invoice_flag',
                 'is_frist_step', 'is_second_step', 'is_third_step', 'is_fourth_step', 'is_fifth_step', 'is_sixth_step', 'btn_state')
    def _compute_state(self):
        """ 状态位控制 """
        for s in self:
            if s.step_one and s.is_frist_step:
                s.write({'state': SHIP_ORDER_STATE[1][0]})
                if s.step_two and s.is_second_step:
                    s.write({'state': SHIP_ORDER_STATE[2][0]})
                    if s.step_three and s.is_third_step:
                        s.write({'state': SHIP_ORDER_STATE[3][0]})
                        if s.step_four and s.is_fourth_step:
                            s.write({'state': SHIP_ORDER_STATE[4][0]})
                            if s.step_five and s.is_fifth_step:
                                s.write({'state': SHIP_ORDER_STATE[5][0]})
                                if s.step_six and s.is_sixth_step:
                                    s.write({'state': SHIP_ORDER_STATE[6][0]})
                                    if s.pay_flag:
                                        if len(s.shipment_ids.ids) == 0:
                                            s._create_shipment()
                                        if not s.invoice_flag:
                                            s.write({'state': SHIP_ORDER_STATE[7][0]})
                                        else:
                                            s.write({'state': SHIP_ORDER_STATE[9][0]})
                                    if s.fail_flag:
                                        s.write({'state': SHIP_ORDER_STATE[8][0]})
                                    # if len(s.shipment_ids.ids) == 0:
                                    #     s._create_shipment()
                                    # s.write({'state': SHIP_ORDER_STATE[7][0]})

    @api.depends('mail_route_sale_adjusted_price', 'fulfillment_total_sale_adjusted_price', 'value_added_total_sale_adjusted_price')
    def _depends_compute_actual_price(self):
        """ 计算实价 """
        for s in self:
            total_actual_price = s.mail_route_sale_adjusted_price + s.fulfillment_total_sale_adjusted_price + s.value_added_total_sale_adjusted_price

            s.write({'mail_route_actual_price': s.mail_route_sale_adjusted_price,
                     'fulfillment_total_actual_price': s.fulfillment_total_sale_adjusted_price,
                     'value_added_total_actual_price': s.value_added_total_sale_adjusted_price,
                     'total_actual_price': total_actual_price})

    @api.depends('shipment_ids')
    def _depends_compute_shipment_number(self):
        for s in self:
            if s.shipment_ids:
                s.write({'shipment_number': len(s.shipment_ids),
                         'shipment_flag': True if len(s.shipment_ids.filtered(lambda i: i.active_flag == True)) > 0 else False})

    """
    Onchange
    """

    @api.onchange('send_country_id')
    def _onchange_send_country_id(self):
        self.send_postal_code_id = False

    @api.onchange('receive_country_id')
    def _onchange_receie_country_id(self):
        self.receive_postal_code_id = False

    @api.onchange('fulfillment_dropoff')
    def _onchange_fulfillment_dropoff(self):
        if self.fulfillment_dropoff:
            self._add_fulfillment(type='dropoff')
        else:
            self._unlink_fulfillment(type='dropoff')

    @api.onchange('fulfillment_pickup')
    def _onchange_fulfillment_pickup(self):
        if self.fulfillment_pickup:
            self._add_fulfillment(type='pickup')
        else:
            self._unlink_fulfillment(type='pickup')

    @api.onchange('fulfillment_collect')
    def _onchange_fulfillment_collect(self):
        if self.fulfillment_collect:
            self._add_fulfillment(type='collect')
        else:
            self._unlink_fulfillment(type='collect')

    @api.onchange('fulfillment_delivery')
    def _onchange_fulfillment_delivery(self):
        if self.fulfillment_delivery:
            self._add_fulfillment(type='delivery')
        else:
            self._unlink_fulfillment(type='delivery')

    @api.onchange('select_value_added_line_ids')
    def _onchange_select_value_added_line_ids(self):
        select_added_ids_list = self.select_value_added_line_ids.ids
        ship_added_ids_list = self.rp_ship_order_value_added_line_ids.filtered(lambda x: x.value_added_category != 'one').mapped('value_added_id').mapped('id')
        # # 需要向明细行中添加的增值服务
        add_value_list = list(set(select_added_ids_list) - set(ship_added_ids_list))
        # # 需要在明细行中删除的增值服务
        del_value_list = list(set(ship_added_ids_list) - set(select_added_ids_list))
        if len(add_value_list) > 0:
            for select_added_id in self.select_value_added_line_ids:
                ship_added_ids = self.rp_ship_order_value_added_line_ids.filtered(lambda x: x.value_added_category != 'one').mapped('value_added_id').mapped('id')
                # 如果选择的增值服务没有在明细行中，向明细行中添加
                if select_added_id.ids[0] not in ship_added_ids:
                    available_sva_values = ShipOrder(self.env).backdoor_get_available_sva(self.shipper_mail_route_id)
                    filtered_data = list(filter(lambda x: x['value_added_id'] in select_added_id.ids, available_sva_values))
                    available_svas = self.env['rp.available.shipper.value.added.tran'].create(filtered_data)
                    for available_sva in available_svas:
                        self.write({'rp_ship_order_value_added_line_ids': [(0, 0, {'rp_ship_order_id': self.ids[0],
                                                                                   'value_added_id': available_sva.value_added_id.id,
                                                                                   'value_added_type': available_sva.value_added_type,
                                                                                   'value_added_category': available_sva.value_added_category,
                                                                                   'tag_price': available_sva.tag_price,
                                                                                   'sale_adjusted_price': available_sva.sale_adjusted_price,
                                                                                   'used_sale_price_adjust_ids': [(6, 0, available_sva.used_sale_price_adjust_ids.ids)]}
                                                                            )]})
        # 如果明细行中的增值服务没有在选择中，在明细行中删除
        if len(del_value_list) > 0:
            ship_added_ids = self.rp_ship_order_value_added_line_ids.filtered(lambda x: x.value_added_category != 'one')
            for ship_added_id in ship_added_ids:
                if ship_added_id.value_added_id.id not in self.select_value_added_line_ids.ids:
                    self.rp_ship_order_value_added_line_ids = [(3, ship_added_id.id)]

    @api.onchange('rp_ship_order_value_added_line_ids')
    def _onchange_rp_ship_order_value_added_line_ids(self):
        """
        增值服务明细和已选增值服务保持一致
        """
        ship_added_ids = self.rp_ship_order_value_added_line_ids.filtered(lambda x: x.value_added_category != 'one').mapped('value_added_id')
        # 增值服务明细和已选增值服务保持一致
        self.select_value_added_line_ids = [(6, 0, ship_added_ids.mapped('id'))]

    @api.onchange('need_invoice')
    def _onchange_need_invoice(self):
        if self.state == 'invoiced':
            raise UserError('该订单已经开发票，不能修改此信息！')
        if not self.need_invoice:
            # if not all([self.send_postal_code_id, self.send_state_id, self.send_city_id, self.send_street, self.send_street2,
            #             self.send_last_name, self.send_first_name, self.send_phone, self.send_address_type, self.send_email]):
            #     raise UserError('需要填充发件地址后重试！')
            self.update({
                'copy_from_sender': False,
                'invoice_postal_code_id': False,
                'invoice_state_id': False,
                'invoice_city_id': False,
                'invoice_receive_street': False,
                'invoice_receive_street2': False,
                'invoice_first_name': False,
                'invoice_last_name': False,
                'invoice_phone_number': False,
                'invoice_address_type': False,
                'invoice_email': False,
                'invoice_company_name': False
            })

    @api.onchange('copy_from_sender')
    def _onchange_copy_from_sender(self):
        if self.state == 'invoiced':
            raise UserError('该订单已经开发票，不能修改此信息！')
        if self.copy_from_sender:
            self.update({
                'invoice_postal_code_id': self.send_postal_code_id.id,
                'invoice_state_id': self.send_state_id.id,
                'invoice_city_id': self.send_city_id.id,
                'invoice_receive_street': self.send_street,
                'invoice_receive_street2': self.send_street2,
                'invoice_first_name': self.send_first_name,
                'invoice_last_name': self.send_last_name,
                'invoice_phone_number': self.send_phone,
                'invoice_address_type': self.send_address_type,
                'invoice_email': self.send_email,
                'invoice_company_name': self.send_company_name
            })

    @api.onchange('invoice_postal_code_id', 'invoice_state_id', 'invoice_city_id', 'invoice_receive_street',
                  'invoice_receive_street2', 'invoice_first_name', 'invoice_last_name', 'invoice_phone_number', 'invoice_address_type', 'invoice_email', 'invoice_company_name')
    def _onchange_invoice_related_fields(self):
        if self.state == 'invoiced':
            raise UserError('订单已经开票，不能修改发票的信息！')

    """
    Button Function
    """

    def action_get_available_shipper_mail_route(self):
        """ 获取可用的托运商服务 """
        if self.state == SHIP_ORDER_STATE[7][0]:
            raise UserError('该订单已完成，不允许修改')
        smr_values = ShipOrder(self.env).backdoor_get_available_smr(send_city=self.send_city_id,
                                                                    receive_city=self.receive_city_id,
                                                                    package_type=self.package_type_id,
                                                                    parcel_total_weight=self.parcel_total_weight,
                                                                    parcel_total_volume=self.parcel_total_volume)
        # 创建向导模型
        available_smr = self.env['rp.available.shipper.mail.route.tran'].create(smr_values)
        action = self.env.ref('rp_shipment_management.action_rp_available_shipper_mail_route_tran')
        result = action.read()[0]

        result['name'] = '可用托运商邮路'
        result['domain'] = "[('id','in',%s)]" % available_smr.ids
        result['context'] = {'create': False,  # 不允许创建
                             'ship_order_id': self.id,
                             'send_postal_code': self.send_postal_code_id.id,
                             'receive_postal_code': self.receive_postal_code_id.id}  # 传递主表ID,方便回写
        result['display_name'] = None
        result['target'] = 'new'
        return result

    def action_get_available_fulfillment(self):
        """ 获取可用头尾程 """
        if self.state == SHIP_ORDER_STATE[7][0]:
            raise UserError('该订单已完成，不允许修改')
        if not self.shipper_mail_route_id:
            raise UserError('没有托运商邮路，请执行完第三步再进行该操作')
        available_sff_values = ShipOrder(self.env).backdoor_get_fulfillment(self.shipper_mail_route_id)
        # 创建向导模型
        available_sff = self.env['rp.available.shipper.fulfillment.tran'].create(available_sff_values)

        action = self.env.ref('rp_shipment_management.action_rp_available_shipper_fulfillment_tran')
        result = action.read()[0]

        result['name'] = '可用头尾程'
        result['domain'] = "[('id','in',%s)]" % available_sff.ids
        result['context'] = {'create': False,  # 不允许创建
                             'ship_order_id': self.id}  # 传递主表ID,方便回写
        result['display_name'] = None
        result['target'] = 'new'
        return result

    def action_get_available_value_added(self):
        """ 获取可用增值服务 """
        if self.state == SHIP_ORDER_STATE[7][0]:
            raise UserError('该订单已完成，不允许修改')
        if not self.shipper_id:
            raise UserError('没有托运商，请执行完第三步再进行该操作')
        available_sva_values = ShipOrder(self.env).backdoor_get_available_sva(self.shipper_mail_route_id)
        # 创建向导模型
        available_sva = self.env['rp.available.shipper.value.added.tran'].create(available_sva_values)

        action = self.env.ref('rp_shipment_management.action_rp_available_shipper_value_added_tran')
        result = action.read()[0]

        result['name'] = '可用增值服务'
        result['domain'] = "[('id','in',%s)]" % available_sva.ids
        result['context'] = {'create': False,  # 不允许创建
                             'ship_order_id': self.id}  # 传递主表ID,方便回写
        result['display_name'] = None
        result['target'] = 'new'
        return result

    def action_get_available_customer_address(self):
        """ 获取可用的客户地址 """
        if self.state == SHIP_ORDER_STATE[7][0]:
            raise UserError('该订单已完成，不允许修改')
        if not self.customer_id:
            raise UserError('该功能只有在已输入客户的时候可用')
        available_cad = ShipOrder(self.env).backdoor_get_available_customer_address(customer=self.customer_id)

        action = self.env.ref('rp_shipment_management.action_rp_available_customer_address_tran')
        result = action.read()[0]

        result['name'] = '可用客户地址'
        result['domain'] = "[('id','in',%s)]" % available_cad.ids
        result['context'] = {'create': False,  # 不允许创建
                             'ship_order_id': self.id}  # 传递主表ID,方便回写
        result['display_name'] = None
        result['target'] = 'new'
        return result

    # 上一步按钮
    def button_change_btn_state_back(self):
        ShipOrder(self.env).button_change_btn_state_back(self.id)

    # 下一步按钮
    def button_change_btn_state_next_1(self):
        ShipOrder(self.env).button_change_btn_state_next(self.id)

    def button_change_btn_state_next_2(self):
        ShipOrder(self.env).button_change_btn_state_next(self.id)

    # 六步完成按钮
    def button_change_state_finish(self):
        ShipOrder(self.env).button_change_btn_state_next(self.id)

    def action_for_pay(self):
        """
        支付成功回调修改订单状态和记录流水需要
        """
        if self.state != SHIP_ORDER_STATE[6][0]:
            raise UserError('当前不在待支付状态')
        # 更改支付单状态
        payment_code = self.env.context.get('payment_code')
        if payment_code:
            order_payment_id = self.env['rp.payment'].search([('code', '=', payment_code.strip())])
            # 支付单状态修改为支付完成
            order_payment_id.write({'state': 'pay', 'success_paytime': fields.Datetime.now()})
            self.write({'pay_flag': True})  # 订单状态为支付完成
            # 支付完成后如果需要开票进行开票
            if self.need_invoice:
                order_payment_id.gene_invoice([self])
            # 记录流水信息
            # self.record_flow_info()

    def action_for_fail(self):
        """
        支付失败的处理逻辑
        """
        if self.state != SHIP_ORDER_STATE[6][0]:
            raise UserError('当前不在待支付状态')
        order_payment_id = self.env['rp.payment'].search([('advance_document_id.field_record_id', '=', self.id)])
        order_payment_id.write({'state': 'error'})
        self.write({'fail_flag': True})

    def forward_to_pay(self):
        """
        触发支付向导的方法
        """
        if self.state != SHIP_ORDER_STATE[6][0]:
            raise UserError('当前不在待支付状态')
        # 生成支付单
        rp_ship_order_payment_id = ShipOrderFC(self.env).gene_payment(self)
        # 打开视图
        # 查看是否有历史的最后一次的向导视图
        pay_tran_id = self.env['rp.ship.order.action.pay.tran'].search([('order_code', '=', self.code)], order='create_date DESC')
        action = self.env.ref('rp_shipment_management.rp_ship_order_action_pay_tran_view_action')
        # 订单总价使用分项精确后的值
        mail_route_actual_price = round(self.mail_route_actual_price, 2)
        fulfillment_actual_price = round(self.fulfillment_total_actual_price, 2)
        value_added_actual_price = round(self.value_added_total_actual_price, 2)
        total_actual_price = round(mail_route_actual_price + fulfillment_actual_price + value_added_actual_price, 2)
        result = action.read()[0]
        result['name'] = '订单支付向导'
        result['context'] = {
            'create': False,  # 不允许创建
            'customer_id': self.customer_id.id,
            'order_total_price': total_actual_price,
            'order_code': self.code,
            'show_display': True,
            'rp_ship_order_payment_id': rp_ship_order_payment_id.id
        }
        result['target'] = 'new'
        if pay_tran_id:
            result['res_id'] = pay_tran_id.id
        return result

    def action_open_shipment(self):
        """ 打开相关的运单视图 """
        self.ensure_one()
        action = self.env.ref('rp_shipment_management.action_rp_shipment')
        result = action.read()[0]
        view_form = self.env.ref('rp_shipment_management.rp_shipment_form', False)
        if len(self.shipment_ids) == 1:
            result['views'] = [(view_form and view_form.id or False, 'form')]
            result['res_id'] = self.shipment_ids.ids[0]
        else:
            result['view_mode'] = 'list,form'
            result['context'] = {'search_default_is_use': 1, 'search_default_not_use': 1}
            result['domain'] = [('id', 'in', self.shipment_ids.ids)]
        return result

    @api.model
    def action_aggregate_ship_order(self, active_ids=None):
        """
        聚合并校验订单数据
        Params:
        -active_ids:活跃的记录ID
        """
        rp_ship_order_model_id = self.env['ir.model'].search([('model', '=', self._name)])
        rp_ship_order_ids = self.env['rp.ship.order'].search([('id', 'in', active_ids)])
        # 已完成订单错误
        error_records = rp_ship_order_ids.filtered(lambda r: r.state != 'done')
        # 不是一个用户的选择错误
        customer_id = rp_ship_order_ids.mapped(lambda r: r.customer_id.id)
        if len(set(customer_id)) != 1:
            raise Exception('您选择的订单不是同一个客户，请重新选择！')
        if len(error_records.ids) != 0:
            raise Exception('您选择的订单中存在未支付或已开票的订单，请重新选择！')
        action = self.env.ref('rp_finance_management.rp_invoice_address_tran_view_action')
        view_form = self.env.ref('rp_finance_management.rp_invoice_address_tran_form_view', False)
        result = action.read()[0]
        result['views'] = [(view_form.id, 'form')]
        result['name'] = '发票地址填充向导'
        result['views'] = [(view_form.id, 'form')]
        result['context'] = {'active_ids': active_ids, 'model_id': rp_ship_order_model_id.id}
        result['target'] = 'new'
        return result

    def action_open_payment(self):
        """
        打开对应支付单视图
        """
        self.ensure_one()
        action = self.env.ref('rp_finance_management.rp_payment_action')
        result = action.read()[0]
        view_form = self.env.ref('rp_finance_management.rp_payment_form_view', False)
        payment_id = self.env['rp.payment'].search([('advance_document_id.field_record_id', '=', self.id), ('advance_document_id.field_name_id', '=', self._name)], limit=1)
        result['views'] = [(view_form.id, 'form')]
        result['res_id'] = payment_id.id
        return result

    def action_open_invoiced(self):
        """
        打开开票窗口
        """
        self.ensure_one()
        action = self.env.ref('rp_finance_management.rp_finance_invoice_view_action')
        result = action.read()[0]
        view_form = self.env.ref('rp_finance_management.rp_finance_invoice_form_view', False)
        invoice_id = self.env['rp.finance.invoice'].search([('advanced_document_ids.field_record_id', 'in', [self.id])], limit=1)
        result['views'] = [(view_form.id, 'form')]
        result['res_id'] = invoice_id.id
        return result

    def turn_balance(self):
        """
        流程控制余额页
        """
        self.ensure_one()
        self.write({'process_step': 'balance'})

    def turn_pay(self):
        """
        流程控制支付页
        """
        self.ensure_one()
        self.write({'process_step': 'pay'})

    def test(self):
        self.write({'state': 'unpaid',
                    'pay_flag': False,
                    'shipment_ids': False})

    def test_label(self):
        print('1111111')
